package com.suneast.suneaststore.modules.personal.address;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import com.suneast.suneaststore.R;
import com.suneast.suneaststore.bean.personal.address.AddressBean;
import com.suneast.suneaststore.bean.personal.address.AreaBean;
import com.suneast.suneaststore.modules.personal.address.event.AddAddressResult;
import com.suneast.suneaststore.modules.personal.address.event.GotAddressInfo;
import com.suneast.suneaststore.modules.personal.address.event.ModifyAddressResult;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.ui.fragments.BaseFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;

public class AddressEditFragment extends BaseFragment {
    private static final int REQUEST_AREA_CODE = 0;
    public static final int RESULT_CODE_SUCCEED = 1;

    @Override
    public int setLayout() {
        return R.layout.fragment_edit_address;
    }

    ArrayList<AreaBean> curAreaList = null;

    int addressId = -1;

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        EventBus.getDefault().register(this);
        addressId = getArguments().getInt("id", -1);
        initData();
        addressBean.setId(addressId);
        initView();
        if (addressId != -1) {
            AddressHandler.requestAddressInfo(addressId);
        } else {
            AddressHandler.requestProvinceList();
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_AREA_CODE) {
            if (resultCode == RESULT_CODE_SUCCEED) {
                addressBean.setPid(data.getInt("pid"));
                addressBean.setCid(data.getInt("cid"));
                addressBean.setAid(data.getInt("aid"));
                addressBean.setTid(data.getInt("tid"));
                addressBean.setProvince(data.getString("province"));
                addressBean.setCity(data.getString("city"));
                addressBean.setArea(data.getString("area"));
                addressBean.setTown(data.getString("town"));
                areaEt.setText(addressBean.getProvince()
                        + " " + addressBean.getCity()
                        + " " + addressBean.getArea()
                        + " " + addressBean.getTown());
            }
        }
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @OnClick({R.id.btn_save_address, R.id.et_area})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.btn_save_address: {
                Log.e("test", "onViewClick: addressId = " + addressId);
                if (addressId != -1) {
                    AddressHandler.modifyAddress(addressBean);
                } else {
                    Log.e("test", "onViewClick: addAddress = ");
                    AddressHandler.addAddress(addressBean);
                }
            }
            break;
            case R.id.et_area: {
                InputMethodManager imm = (InputMethodManager) _mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(consigneeEt.getWindowToken(), 0);
                }
                AreaSelectFragment fragment = new AreaSelectFragment();
                Bundle bundle = new Bundle();
                bundle.putInt("id", addressId);
                bundle.putInt("pid", addressBean.getPid());
                bundle.putInt("cid", addressBean.getCid());
                bundle.putInt("aid", addressBean.getAid());
                bundle.putInt("tid", addressBean.getTid());
                bundle.putString("province", addressBean.getProvince());
                bundle.putString("city", addressBean.getCity());
                bundle.putString("area", addressBean.getArea());
                fragment.setArguments(bundle);
                startForResult(fragment, REQUEST_AREA_CODE);
            }
            break;
        }
    }

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.et_consignee)
    EditText consigneeEt;
    @BindView(R.id.et_contact_number)
    EditText contactNumberEt;
    @BindView(R.id.et_area)
    EditText areaEt;
    @BindView(R.id.et_detailed_address)
    EditText detailedAddressEt;
    @BindView(R.id.cb_set_default)
    CheckBox setDefaultCb;

    private void initData() {
        addressBean = new AddressBean();
        curAreaList = new ArrayList<>(4);
        for (int i = 0; i < 4; i++) {
            curAreaList.add(new AreaBean());
        }
    }

    private void initView() {
        toolbar.setNavigationOnClickListener(v -> pop());
        consigneeEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                addressBean.setRealname(s.toString());
            }
        });
        contactNumberEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                addressBean.setMobile(s.toString());
            }
        });
        detailedAddressEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                addressBean.setAddress(s.toString());
            }
        });
        setDefaultCb.setOnCheckedChangeListener((CompoundButton buttonView, boolean isChecked) -> {
            addressBean.setIsdefault(isChecked ? 1 : 0);
        });
    }

    GotAddressInfo addressInfo = null;
    AddressBean addressBean = null;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotAddressInfo(GotAddressInfo event) {
        addressInfo = event;
        addressBean = event.getAddressBean();
        consigneeEt.setText(addressBean.getRealname());
        contactNumberEt.setText(addressBean.getMobile());
        areaEt.setText(addressBean.getProvince()
                + " " + addressBean.getCity()
                + " " + addressBean.getArea()
                + " " + addressBean.getTown());
        detailedAddressEt.setText(addressBean.getAddress());
        setDefaultCb.setChecked(addressBean.getIsdefault() == 1);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onModifyAddressResult(ModifyAddressResult event) {
        if (event.getResult() == Flag.Result.SUCCEED) {
            Toast.makeText(getContext(), "地址修改成功", Toast.LENGTH_SHORT).show();
            setFragmentResult(AddressListFragment.MODIFY_ADDRESS_RESULT, new Bundle());
            pop();
        } else {
            Toast.makeText(getContext(), "地址修改失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAddAddressResult(AddAddressResult event) {
        if (event.getResult() == Flag.Result.SUCCEED) {
            Toast.makeText(getContext(), "地址添加成功", Toast.LENGTH_SHORT).show();
            setFragmentResult(AddressListFragment.ADD_ADDRESS_RESULT, new Bundle());
            pop();
        } else {
            Toast.makeText(getContext(), "地址添加失败", Toast.LENGTH_SHORT).show();
        }
    }
}
